/**
 * Copyright (c) 2009 Cerner Corporation.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Cerner Corporation - initial API and implementation
 */
package com.cerner.system.rest.resource.organizer;

import static java.util.Collections.unmodifiableSet;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import com.cerner.system.rest.resource.organizer.spi.NotThreadSafe;
import com.cerner.system.rest.resource.organizer.spi.ResourceKey;
import com.cerner.system.rest.resource.organizer.spi.ResourceRef;

/**
 * Internal class that maintains the representation of a resource and any
 * associated keys that are affected when deleting it from the tree. Objects of
 * type {@link ResourceRef} are not thread-safe.
 * 
 * @author Alex Horn
 * @param <E> class type of the object that is stored in the tree data structure
 */
@NotThreadSafe
class MapResourceRef<E> implements ResourceRef<E> {

  /**
   * Reference to resource representation. It may be {@code null} when the
   * resource node only needs to maintain {@link #descendants} information.
   */
  private E representation;

  /**
   * Set of URI keys that are descendants of a particular resource in the tree.
   * These keys identify resources that are effected if this cache data is
   * deleted from the underlying container data structure.
   */
  private final Set<ResourceKey> descendants;

  /**
   * Instantiate a new non-thread-safe {@link MapResourceRef} object.
   */
  MapResourceRef() {
    this.descendants = new HashSet<ResourceKey>();
  }

  public E get() {
    return this.representation;
  }

  public E set(final E representation) {
    final E _representation = this.representation;
    this.representation = representation;
    return _representation;
  }

  /**
   * Internal API that registers additional keys of resource nodes that are
   * affected if this {@link MapResourceRef} will be removed from the underlying
   * tree data structure.
   * 
   * @param descendants additional keys of resources that are affected if this
   *          node is deleted
   */
  @SuppressWarnings("hiding" /* see "this" prefix */)
  void update(final Collection<ResourceKey> descendants) {
    this.descendants.addAll(descendants);
  }

  /**
   * Internal API to obtain an unmodifiable set of descendant keys. The keys
   * identify resources that are affected if this node is deleted from the
   * underlying tree data structure.
   * 
   * @return unmodifiable collection of descendant keys
   */
  Collection<ResourceKey> descendants() {
    return unmodifiableSet(this.descendants);
  }

}
